package edu.jhmi.tools.omssa_gui;

/**
 * @author Ravi Tharakan
 * @author Lennart Martens
 *
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

// a simple ancestor class to reduce code duplication in formatdb and omssacl
// process builders

public abstract class OmssaguiProcessBuilder {
    ArrayList process_name_array = new ArrayList();
    ProcessBuilder pb;
    Process p;

    /**
     * Trivial constructor.
     */
    public OmssaguiProcessBuilder () {
    }

    /**
     * Checks the operating system by looking at the JVM os.name variable
     */
    public void checkOperatingSystem () {
        String operating_system = System.getProperty("os.name");
        if (operating_system.contains("Mac OS")) {
            process_name_array.add("open");
        }
    }

    /**
     * Starts the process of a process builder, gets the inputstream from the
     * process and shows it in a JTextArea. Does not close until the process
     * is completed.
     *
     * @return Process the process started.
     */
    public void startProcess() {
        p = null;
        try {
            p = pb.start();
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            ioe.printStackTrace();
        }
        // get inputstream from process, set up text area
        Scanner scan = new Scanner(p.getInputStream());
        // auxiliary string to show output on both std out and text box
        String temp;
        // get input from scanner, send to std out and box
        while (scan.hasNext()) {
            temp = scan.next();
            System.out.print(temp + " ");
        }
        scan.close();
        // wait for process to terminate before exiting
        
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            if(p != null) {
                p.destroy();
            }
        }
    }

    public void endProcess() {
        p.destroy();
    }
}
